package br.edu.utfpr.md.tads.controller.connections;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.util.Xml;
import br.edu.utfpr.md.tads.model.Contato;

public class ContatosConnection extends Connection implements Metodos<Contato> {

	public ContatosConnection(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	public ArrayList<Contato> getAll() {
		String content = httpGet(GET_JSON_CONTATOS);
		return stringToContato(content);
	}

	@Override
	public Contato getById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean post(Contato t) {
		return httpPost(POST_XML_CONTATOS, ObjectToString(t));
	}

	@Override
	public boolean put(Contato t) {
		return httpPut(PUT_XML_CONTATOS+t.getId(),ObjectToString(t));
	}

	@Override
	public boolean delete(String delete) {
		return httpDelete(DELETE_CONTATOS+delete);
	}

	public ArrayList<Contato> getBuscar(String string) {
		String content = httpGet(GET_BUSCA_CONTATOS + string);
		return stringToContato(content);
	}

	protected ArrayList<Contato> stringToContato(String content) {
		ArrayList<Contato> contatos = new ArrayList<Contato>();
		if (content != null) {
			try {
				JSONObject object = (JSONObject) new JSONTokener(content).nextValue();
				Object json = new JSONTokener(object.getString("contato")).nextValue();
				if (json instanceof JSONObject) {
					JSONObject obt = (JSONObject) json;
					Contato contato = new Contato();
					contato.setId(obt.getString("id"));
					contato.setNome(obt.getString("nome"));
					contato.setSobreNome(obt.getString("sobreNome"));
					contato.setNumero(obt.getString("numero"));
					contato.setBairro(obt.getString("bairro"));
					contato.setCidade(obt.getString("cidade"));
					contato.setEndereco(obt.getString("endereco"));
					List<String> telefones = new ArrayList<String>();
					Object ObjetoTelefone = new JSONTokener(obt.getString("telefones")).nextValue();
					
					if (ObjetoTelefone instanceof JSONArray) {
						JSONArray telo = obt.getJSONArray("telefones");
						for (int j = 0; j < telo.length(); j++) {
							telefones.add(telo.getString(j));
						}
					}else{
						telefones.add(obt.getString("telefones"));
					}
					contato.setTelefones(telefones);
					contatos.add(contato);
				} else if (json instanceof JSONArray) {
					JSONArray jAC = (JSONArray) json;
					for (int i = 0; i < jAC.length(); i++) {
						JSONObject obt = jAC.getJSONObject(i);
						Contato contato = new Contato();
						contato.setId(obt.getString("id"));
						contato.setNome(obt.getString("nome"));
						contato.setSobreNome(obt.getString("sobreNome"));
						contato.setNumero(obt.getString("numero"));
						contato.setBairro(obt.getString("bairro"));
						contato.setCidade(obt.getString("cidade"));
						contato.setEndereco(obt.getString("endereco"));

						List<String> telefones = new ArrayList<String>();
						Object ObjetoTelefone = new JSONTokener(obt.getString("telefones")).nextValue();
						
						if (ObjetoTelefone instanceof JSONArray) {
							JSONArray telo = obt.getJSONArray("telefones");
							for (int j = 0; j < telo.length(); j++) {
								telefones.add(telo.getString(j));
							}
						}else{
							telefones.add(obt.getString("telefones"));
						}
						contato.setTelefones(telefones);
						contatos.add(contato);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return contatos;
	}

	private String ObjectToString(Contato contato) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "contato");

			serializer.startTag("", "id");
			serializer.text(contato.getId());
			serializer.endTag("", "id");

			serializer.startTag("", "nome");
			serializer.text(contato.getNome());
			serializer.endTag("", "nome");

			serializer.startTag("", "sobreNome");
			serializer.text(contato.getSobreNome());
			serializer.endTag("", "sobreNome");

			serializer.startTag("", "numero");
			serializer.text(contato.getNumero());
			serializer.endTag("", "numero");

			serializer.startTag("", "endereco");
			serializer.text(contato.getEndereco());
			serializer.endTag("", "endereco");

			serializer.startTag("", "bairro");
			serializer.text(contato.getBairro());
			serializer.endTag("", "bairro");
			
			serializer.startTag("", "cidade");
			serializer.text(contato.getCidade());
			serializer.endTag("", "cidade");

			for (String telefone : contato.getTelefones()) {
				serializer.startTag("", "telefones");
				serializer.text(telefone);
				serializer.endTag("", "telefones");
			}
			serializer.endTag("", "contato");

			serializer.endDocument();
			return writer.toString();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}
}
